package com.xgp.laboratorymanagementsystem.controller;

import com.google.code.kaptcha.Constants;
import com.xgp.laboratorymanagementsystem.model.User;
import com.xgp.laboratorymanagementsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.regex.Pattern;

@RestController("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据用户名密码查找该用户是否存在，若存在，则查出用户信息
     */
    @RequestMapping("/user/loginMethod")
    public int loginMethod(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("code") String code,
            HttpSession session
    ) {
        String realcode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);

        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        if(!pattern.matcher(username).matches()) {
            return 1;
        }

        if(code != null && !code.isEmpty() && realcode.equals(code)) {
            //验证码通过
            //1，通过用户名和密码查询该用户，并返回
            User user = userService.fingLoginUser(username,password);
            //2，比较权限，看是否给予登陆
            if(user == null) {
                return 1;
            }

            if(user.getRoot() == 0) {
                return 2;
            }
            //3，保存用户信息
            session.setAttribute("loginUser",user);
            return 3;
        }
        return 0;
    }
}
